package com.liuqi.aiagent.controller;

import com.liuqi.aiagent.ai.chat.ChatException;
import com.liuqi.aiagent.service.ChatService;
import com.liuqi.aiagent.transfer.dto.AgentChatDto;
import com.liuqi.aiagent.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import static com.liuqi.aiagent.util.StringUtil.notHasText;

/**
 * @author liuqi
 * @date 2025/7/18
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/api")
@Slf4j
@Api(tags = "Ai Chat 服务接口")
public class ChatController {

    private final ChatService chatService;

    @ApiOperation("openai 对话")
    @PostMapping("/chat/completions")
    public ResponseBodyEmitter chatCompletions(HttpServletRequest request,
                                               HttpServletResponse response,
                                               @RequestBody AgentChatDto agentChat) {
        if (notHasText(agentChat.getAgentName())) {
            ResponseUtil.responseError(response, "agentName为空");
            return null;
        }
        if (notHasText(agentChat.getUsername())) {
            ResponseUtil.responseError(response, "username为空");
            return null;
        }
        if (notHasText(agentChat.getInput())) {
            ResponseUtil.responseError(response, "对话内容为空");
            return null;
        }
        if (agentChat.getTimeout() != null) {
            int timeout = agentChat.getTimeout();
            if (timeout < 1) {
                ResponseUtil.responseError(response, "超时时间不能小于1分钟");
                return null;
            }
            if (timeout > 10) {
                ResponseUtil.responseError(response, "超时时间不能大于10分钟");
                return null;
            }
        }
        try {
            return chatService.chatCompletions(agentChat);
        } catch (ChatException e) {
            log.error("对话异常", e);
            ResponseUtil.responseError(response, "系统服务异常,请联系管理员处理");
        }
        return null;
    }

}
